package com.xgq.drink.service.impl;

import com.xgq.drink.entity.AttributeProduct;
import com.xgq.drink.entity.Cart;
import com.xgq.drink.mapper.AttributeProductMapper;
import com.xgq.drink.mapper.CartMapper;
import com.xgq.drink.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Autowired
    private AttributeProductMapper attributeProductMapper;

    @Override
    public boolean addCartItem(Cart cart) {
        // 查询 attribute_product 表获取价格
        AttributeProduct attributeProduct = attributeProductMapper.selectOne(
                new QueryWrapper<AttributeProduct>().eq("attribute_id", cart.getAttributeId()).eq("is_del", 0)
        );
        if (attributeProduct == null) {
            throw new RuntimeException("商品属性不存在");
        }
        // 使用 attribute_product 表中的价格
        BigDecimal attributePrice = attributeProduct.getPrice();
        cart.setAddPrice(attributePrice);
        cart.setIsDel(0);
        // 检查购物车中是否已存在该商品
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", cart.getUserId())
                .eq("product_id", cart.getProductId())
                .eq("is_del", 0);

        Cart existingCart = getOne(queryWrapper);

        if (existingCart != null) {
            // 如果已存在，增加数量
            existingCart.setQuantity(existingCart.getQuantity() + cart.getQuantity());
            return updateById(existingCart);
        } else {
            // 如果不存在，新增记录
            return save(cart);
        }
    }

    @Override
    public boolean deleteCartItem(Long cartId) {
        Cart cart = getById(cartId);
        if (cart != null) {
            cart.setIsDel(1); // 逻辑删除
            return updateById(cart);
        }
        return false;
    }

    @Override
    public boolean updateCartItem(Cart cart) {
        return updateById(cart);
    }

    @Override
    public IPage<Cart> getCartItems(Long userId, int page, int size) {
        Page<Cart> cartPage = new Page<>(page, size);
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("is_del", 0);
        return page(cartPage, queryWrapper);
    }
}